#!/bin/sh
set -e

# 检查环境变量
check_env() {
    # 如果没有设置 HOST_IP，使用默认值
    if [ -z "$HOST_IP" ]; then
        export HOST_IP=$(hostname -i)
        echo "HOST_IP not set, using $HOST_IP"
    fi
}

# 检查数据目录权限
check_data_dir() {
    if [ ! -w "/app/data" ]; then
        echo "Error: /app/data directory is not writable"
        exit 1
    fi
}

# 等待服务就绪
wait_for_service() {
    local host="$1"
    local port="$2"
    local service="$3"

    echo "Waiting for $service to be ready..."
    for i in $(seq 1 30); do
        nc -z "$host" "$port" >/dev/null 2>&1 && return 0
        sleep 1
    done
    echo "$service is not available"
    exit 1
}

# 主函数
main() {
    check_env
    check_data_dir

    # 启动后端服务
    echo "Starting backend server..."
    NODE_ENV=production node src/server/index.js &
    backend_pid=$!

    # 等待后端服务就绪
    wait_for_service localhost 3001 "backend server"

    # 启动前端服务
    echo "Starting frontend server..."
    DANGEROUSLY_DISABLE_HOST_CHECK=true \
    HOST=0.0.0.0 \
    WDS_SOCKET_PORT=0 \
    npm start &
    frontend_pid=$!

    # 监控子进程
    wait $backend_pid $frontend_pid
}

# 清理函数
cleanup() {
    echo "Cleaning up..."
    kill $(jobs -p) 2>/dev/null
}

# 设置清理钩子
trap cleanup EXIT

# 运行主函数
main